<?php
/**
 * Created by PhpStorm.
 * User: whwyy
 * Date: 2018/4/25 0025
 * Time: 18:38
 */

namespace BeReborn\Web;


use BeReborn\Base\Authorize;
use BeReborn\Base\BaseApplication;
use BeReborn\Base\Config;
use BeReborn\Cache\Redis;
use BeReborn\Core\Qn;
use BeReborn\Database\Connection;
use BeReborn\Error\RestfulHandler;
use BeReborn\Event\Event;
use BeReborn\Http\Request;
use BeReborn\Http\Response;
use BeReborn\Pool\ClientsPool;
use BeReborn\Route\Limits;
use Exception;
use Swoole\WebSocket\Server;
use BeReborn\Service\Http\Server as BServer;

/**
 * Class Init
 *
 * @package BeReborn\Web
 *
 * @property-read Redis $redis
 * @property-read BServer $socket
 * @property-read Request $request
 * @property-read Response $response
 * @property-read RestfulHandler $error
 * @property-read Connection $db
 * @property-read Qn $qn
 * @property-read Config $config
 * @property-read Event $event
 * @property-read ClientsPool $clientsPool
 * @property-read Authorize $auth
 * @property-read Limits $limits
 * @property-read \BeReborn\Pool\Connection $connections
 */
class Application extends BaseApplication
{

	/**
	 * @var string
	 */
	public $id = 'uniqueId';

	/**
	 * @param $argv
	 * @return Server
	 * @throws
	 */
	public function getSwooleServer($argv)
	{
		/** @var BServer $socket */
		$socket = $this->get('socket');
		if (isset($argv[2])) {
			$this->modify($argv, $socket);
		}

		if (!isset($argv[1])) $argv[1] = 'start';

		return $this->checkAction($argv, $socket);
	}

	/**
	 * @param $argv
	 * @param $socket
	 * @return Server
	 * @throws Exception
	 */
	private function checkAction($argv, $socket)
	{
		if (!in_array($argv[1], ['stop', 'start', 'restart'])) {
			exit($this->error('action not exists.'));
		}
		return $this->{$argv[1]}($socket);
	}

	/**
	 * @param BServer $socket
	 * @return mixed
	 * @throws Exception
	 */
	public function start($socket)
	{
		if ($socket->isRunner()) {
			exit($this->error('server is exists'));
		}
		return $socket->coreServerInit();
	}

	/**
	 * @param BServer $socket
	 * @return mixed
	 * @throws Exception
	 */
	public function restart($socket)
	{
		$this->shutdown($socket);

		return $this->start($socket);
	}


	/**
	 * @param BServer $socket
	 */
	public function stop($socket)
	{
		$this->shutdown($socket);
	}


	/**
	 * @param $argv
	 * @param BServer $socket
	 */
	private function modify($argv, $socket)
	{
		if ($argv[2] == 'back') {
			$socket->patchConfig('daemonize', 1);
		} else if ($argv[2] == 'front') {
			$socket->patchConfig('daemonize', 0);
		} else {
			$socket->patchConfig('daemonize', 1);
		}
	}

	/**
	 * @param BServer $server
	 * @return mixed
	 * @throws
	 */
	public function shutdown($server)
	{
		$socket = $this->runtimePath . '/socket.sock';
		if (!file_exists($socket)) {
			return $this->close($server);
		}

		$pathId = file_get_contents($socket);
		@unlink($socket);

		if (empty($pathId)) {
			return $this->close($server);
		}

		exec("kill -TERM $pathId");

		return $this->close($server);
	}

	/**
	 * @param BServer $server
	 * @throws Exception
	 */
	public function close($server)
	{
		echo 'waite.';
		while ($server->isRunner()) {
			echo '.';
			$pids = glob(storage('workerIds') . '/*');
			if (count($pids) < 1) {
				break;
			}
			foreach ($pids as $pid) {
				if (!file_exists($pid)) {
					continue;
				}
				$content = file_get_contents($pid);
				exec("ps -ax | awk '{ print $1 }' | grep -e '^{$content}$'", $output);
				if (count($output) > 0) {
					$this->closeByPid($content);
				} else {
					file_exists($pid) && @unlink($pid);
				}
			}
			usleep(100);
		}
		echo PHP_EOL;
	}


	/**
	 * @param $port
	 * @return bool|array
	 */
	private function isUse($port)
	{
		if (empty($port)) {
			return false;
		}
		exec('netstat -tunlp tcp | grep ' . $port, $output);
		if (empty($output)) {
			return false;
		}
		return $output;
	}

	/**
	 * @param $pid
	 */
	private function closeByPid($pid)
	{
		shell_exec('kill -TERM ' . $pid);
	}

}
